'''
Created on 25/03/2009

@author: eh01
'''
from im.event.eventhandler import BaseEventHandler
from im.ds import dsconstants

class HTTPErrorHandler(BaseEventHandler):
    '''
    Handles HTTP Error Responses
    '''


    def __init__(self):
        '''
        Constructor
        '''
    
    def do(self, data):
        dso = data
        http_request = dso.get_dst(subject=dsconstants.SUBJECT_ROOT,
                    predicate=dsconstants.PREDICATE_HTTP_REQUEST).get_literal()
        lock = dso.get_dst(subject=dsconstants.SUBJECT_ROOT,
                    predicate=dsconstants.PREDICATE_LOCK).get_literal()
        
        error_code = dso.get_dst(subject=dsconstants.SUBJECT_HTTP_ERROR,
                    predicate=dsconstants.PREDICATE_ERROR_CODE).get_literal()
        error_message_dst = dso.get_dst(subject=dsconstants.SUBJECT_HTTP_ERROR,
                    predicate=dsconstants.PREDICATE_ERROR_MESSAGE)
        
        if error_code == 401 and error_message_dst:
            error_message = error_message_dst.get_literal()            
            http_request.send_response(401, 'UNAUTHORIZED') 
            http_request.send_header('WWW-Authenticate', 'Basic realm="eplanning.vic.au"') 
            http_request.send_header('Content-type', 'text/html') 
            http_request.send_header('Connection', 'close')
            http_request.end_headers() 
            http_request.wfile.write('<html><body><h1>' + error_message + '</ h1></ body></ html>')                        
        elif error_message_dst: 
            error_message = error_message_dst.get_literal()
            http_request.send_error(error_code, error_message)
        else:
            http_request.send_error(error_code)         
        lock.release()
        return
        
        